package org.socialresume.client.mvp.view;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.ToggleButton;

/**
 * This class is used to Transform a ToggleButton into {@link HasValue} object by wrapping itself into a bean 
 * 
 * @author Ludovic Meurillon
 */
public class ToggleButtonWrapper implements HasValue<Boolean>{
	
	private HandlerManager localManager;
	private ToggleButton button;
	
	public ToggleButtonWrapper(ToggleButton button) {
		localManager = new HandlerManager(this);
		this.button = button;
		this.button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				setValueFormButton();
			}
		});
	}
	
	private void setValueFormButton(){
		setValue(button.isDown(),true);
	}

	@Override
	public Boolean getValue() {
		return button.isDown();
	}

	@Override
	public void setValue(Boolean value) {
		setValue(value, false);
	}

	@Override
	public void setValue(Boolean value, boolean fireEvents) {
		button.setDown(value);
		if(fireEvents){
			ValueChangeEvent.fire(this, value);
		}
	}

	@Override
	public HandlerRegistration addValueChangeHandler(
			ValueChangeHandler<Boolean> handler) {
		return localManager.addHandler(ValueChangeEvent.getType(), handler);
	}

	@Override
	public void fireEvent(GwtEvent<?> event) {
		localManager.fireEvent(event);
	}
	
}
